//
//  AESInterface.m
//  iHealthEHR
//
//  Created by Joseph Ayo Akinyele on 7/7/10.
//  Copyright 2010 Johns Hopkins University. All rights reserved.
//

#import "HashInterface.h"

void _print_buffer_as_hex(unsigned char* data, size_t len)
{
	size_t i;
	
	for (i = 0; i < len; i++) {
		printf("%02x ", data[i]);
	}
	printf("\n");
}


@implementation HashInterface

-(id) init
{
	if(self = [super init]) {
		// add initialization functions here
		OpenSSL_add_all_digests();
		sha2 = EVP_get_digestbyname(SHA2);
		EVP_MD_CTX_init(&sha2ctx);
		
	}
	
	return self;
}

-(unsigned char *) compute_sha2_hash:(NSArray *) strings
{
	// filter through strings and update the hash structure?
	EVP_DigestInit(&sha2ctx, sha2);
	
	// for loop through strings
	for(int i = 0; i < [strings count]; i++) {
		const char *tmp = [[strings objectAtIndex:i] cStringUsingEncoding:NSASCIIStringEncoding];
		EVP_DigestUpdate(&sha2ctx, tmp, strlen(tmp));
	}
	EVP_DigestFinal(&sha2ctx, sha2_value, (unsigned int *) &sha2_len);
	
	printf("Sha2 hash:\t");
	_print_buffer_as_hex(sha2_value, sha2_len);
	// caller must free
	unsigned char *hash = malloc(sha2_len);
	memcpy(hash, sha2_value, sha2_len);
	printf("Copy of hash:\t");
	_print_buffer_as_hex(hash, sha2_len);
	
	// caller must free 
	return hash;
}

-(void) dealloc
{
	EVP_MD_CTX_cleanup(&sha2ctx);
	[super dealloc];
}

@end
